import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_framework_test/utils/kiline_util.dart';
import 'package:window_manager/window_manager.dart';

import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get_navigation/src/root/get_material_app.dart';

import 'pb/quote/EnKLine.pbenum.dart';
import 'ui/bottom_navigation_bar_page.dart';
import 'utils/logger_manager.dart';
import 'common/app.dart';
import 'config/app_config.dart';
import 'model/event/app_event.dart';

void main() {
  debugPrint(
      '${KLineUtil.getKLineRemainingSeconds(EnKLine.K_LINE_TYPE_1MIN, DateTime.now())}');
  debugPrint('${KLineUtil.getKLineSeconds(EnKLine.K_LINE_TYPE_1MIN)}');

  WidgetsFlutterBinding.ensureInitialized();

  App().init().then((value) {
    runApp(const MyHomePage());
    if (Platform.isAndroid) {
      SystemUiOverlayStyle systemUiOverlayStyle = const SystemUiOverlayStyle(
        statusBarColor: Colors.transparent,
      );
      SystemChrome.setSystemUIOverlayStyle(systemUiOverlayStyle);
    }
  });
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key});
  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage>
    with WidgetsBindingObserver, WindowListener {
  @override
  Future<bool> didPushRouteInformation(RouteInformation routeInformation) {
    return Future.value(true);
  }

  @override
  void didChangePlatformBrightness() {
    super.didChangePlatformBrightness();
    final window = WidgetsBinding.instance.window;
    final brightness = window.platformBrightness;
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
    switch (state) {
      case AppLifecycleState.inactive:
        //应用程序处于闲置状态并且没有收到用户的输入事件。
        //注意这个状态，在切换到后台时候会触发，所以流程应该是先冻结窗口，然后停止UI
        LoggerManager().debug('AppLifecycleState.inactive');
        //EasyLoading.showToast('AppLifecycleState.inactive', toastPosition: EasyLoadingToastPosition.center, maskType: EasyLoadingMaskType.clear, duration: const Duration(seconds: 7));
        break;
      case AppLifecycleState.paused:
        //应用程序处于不可见状态
        LoggerManager().debug('AppLifecycleState.paused');
        //EasyLoading.showToast('AppLifecycleState.paused', toastPosition: EasyLoadingToastPosition.center, maskType: EasyLoadingMaskType.clear, duration: const Duration(seconds: 7));
        break;
      case AppLifecycleState.resumed:
        //进入应用时候不会触发该状态
        //应用程序处于可见状态，并且可以响应用户的输入事件。它相当于 Android 中Activity的onResume。
        LoggerManager().debug('AppLifecycleState.resumed');
        //EasyLoading.showToast('AppLifecycleState.resumed', toastPosition: EasyLoadingToastPosition.center, maskType: EasyLoadingMaskType.clear, duration: const Duration(seconds: 7));
        break;
      case AppLifecycleState.detached:
        //当前页面即将退出
        LoggerManager().debug('AppLifecycleState.detached');
        //EasyLoading.showToast('AppLifecycleState.detached', toastPosition: EasyLoadingToastPosition.center, maskType: EasyLoadingMaskType.clear, duration: const Duration(seconds: 7));
        break;
      case AppLifecycleState.hidden:
        LoggerManager().debug('AppLifecycleState.hidden');
        break;
    }
  }

  @override
  Widget build(BuildContext context) {
    return ScreenUtilInit(
      designSize:
          const Size(AppConfig.designScreenWidth, AppConfig.designScreenHeight),
      minTextAdapt: true,
      splitScreenMode: true,
      builder: (context, child) {
        return GetMaterialApp(
          debugShowCheckedModeBanner: false,
          title: '盯盘神器',
          theme: ThemeData(
            primaryColor: Colors.blueAccent,
            primarySwatch: _createMaterialColor(Colors.blueAccent),
          ),
          home: BottomNavigationBarPage(),
          builder: EasyLoading.init(),
        );
      },
      child: BottomNavigationBarPage(),
    );
  }

  void _registeEventBusListener() {
    App().eventBus.on<AppEvent>().listen((event) {});
  }

  MaterialColor _createMaterialColor(Color color) {
    List strengths = <double>[.05];
    Map<int, Color> swatch = {};
    final int r = color.red, g = color.green, b = color.blue;

    for (int i = 1; i < 10; i++) {
      strengths.add(0.1 * i);
    }
    for (var strength in strengths) {
      final double ds = 0.5 - strength;
      swatch[(strength * 1000).round()] = Color.fromRGBO(
        r + ((ds < 0 ? r : (255 - r)) * ds).round(),
        g + ((ds < 0 ? g : (255 - g)) * ds).round(),
        b + ((ds < 0 ? b : (255 - b)) * ds).round(),
        1,
      );
    }
    return MaterialColor(color.value, swatch);
  }

  @override
  void initState() {
    super.initState();
    // 注册windowManager监听器
    windowManager.addListener(this);
    WidgetsBinding.instance.addObserver(this); //添加观察者
    _registeEventBusListener();
  }

  @override
  void dispose() {
    // 移除windowManager监听器
    windowManager.removeListener(this);
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  // === WindowListener回调 ===
  // 窗口准备关闭时触发
  @override
  void onWindowClose() {
    // 窗口关闭前做一些操作。
    // 我是关闭了adb服务。否则adb服务会一直在运行。
    debugPrint("onWindowClose");
    super.onWindowClose();
  }

  // 窗口获得焦点时触发(比如去浏览器看文章后回来点击本App的窗口)
  @override
  void onWindowFocus() {
    // 获得焦点时做一些处理。我是用于记录记录用户操作，方便后续查找问题及统计活跃情况。
    debugPrint("onWindowFocus");
    super.onWindowFocus();
  }

  // 窗口失去焦点时触发(比如去浏览器看文章了，焦点就不在本App了)
  @override
  void onWindowBlur() {
    // 失去焦点时做一些处理。我是用于记录记录用户操作，方便后续查找问题及统计活跃情况。
    debugPrint("onWindowBlur");
    super.onWindowBlur();
  }

// @override
// Future<bool> didPopRoute() {
//   return Future.value(true);
// }

// @override
// Future<bool> didPushRoute(String route) {
//   return Future.value(true);
// }
}
